#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/18 19:39
# @Author  : huidong.bai
# @File    : androidLogCatchTools.py
# @Software: PyCharm

import os
import sys

curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

import subprocess
import threading
import logging.config
from config import projectPath


# 加载配置文件
logging.config.fileConfig(projectPath.LOG_CONFIG_DIR)
logger = logging.getLogger('my_logger')


def android_adb_log_shell(sn):
    return 'adb -s ' + sn + ' logcat'


def android_write_log(cmd):
    """
    安卓音箱抓取日志方法
    :param cmd: 执行的cmd指令
    :return:
    """
    # 清空adb logcat缓存
    # subprocess.Popen('adb logcat -b all -c', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    logger.info('开始抓取Linux日志:%s...' % cmd)
    log_path = projectPath.ANDROID_CASH_LOG_DIR
    logger.info('存入缓存文件%s中...' % log_path)

    try:
        sub = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        t = threading.currentThread()
        with open(log_path, 'a+', encoding='UTF-8') as fp:
            while getattr(t, "open", True):
                line = sub.stdout.readline().strip()
                # 编码转换，标准输出字节流转string
                log = line.decode("UTF-8", "ignore")
                if len(log):
                    fp.write(log + '\r')
        sub.kill()
    except Exception as e:
        logger.exception(e)
    logger.info('安卓设备日志重定向成功!')
